package bmatch.tech.todo.service.impl;

import bmatch.tech.todo.dao.BmAuthCodeMapper;
import bmatch.tech.todo.dao.BmUserMapper;
import bmatch.tech.todo.model.UserStatus;
import bmatch.tech.todo.model.dataobject.BmAuthCode;
import bmatch.tech.todo.service.AuthCodeService;
import bmatch.tech.todo.service.EmailService;
import bmatch.tech.todo.service.UserService;
import bmatch.tech.todo.util.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @program:todo
 * @author:LinJinhao
 * @create:2019-01-23 17:29
 **/
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

	@Autowired
	private EmailService emailService;

	@Autowired
	private BmAuthCodeMapper bmAuthCodeMapper;

	@Autowired
	private UserService userService;

	@Autowired
	private BmUserMapper bmUserMapper;


	/**
	* 创建激活码
	* @Param: email
	* @return:
	**/
	@Override
	public String generate(String email) {
		String cdKey = IDUtils.get6UUID().toUpperCase();

		BmAuthCode newCode = new BmAuthCode();
		newCode.setId(cdKey);
		newCode.setGmtModified(new Date());
		newCode.setGmtCreated(new Date());
		newCode.setUserId(email);

		bmAuthCodeMapper.insert(newCode);

		String userName[] = email.split("@");
		emailService.send(email,"尊敬的"+userName[0]+"用户","您好！\n您本次的激活码为：\n"+newCode.getId()+"\n请在五分钟内输入，否则失效！");

		return cdKey;
	}

	/**
	*  激活
	* @Param: code 激活码
	* @return:
	**/
	@Override
	public void activate(String code) {
		if (bmAuthCodeMapper.selectById(code) != null){

			String email = bmAuthCodeMapper.selectById(code).getUserId();
			String userId = bmUserMapper.selectByEmail(email).getId();

			userService.activate(userId);
		}
	}
}
